package com.sansan.qiangji.realize.device;

import com.sansan.qiangji.VO.device.ScanVO;
import com.sansan.qiangji.entity.device.Scan;
import com.sansan.qiangji.enums.ResultEnum;
import com.sansan.qiangji.exception.ServiceException;
import com.sansan.qiangji.form.device.scan.ScanAddForm;
import com.sansan.qiangji.form.device.scan.ScanEditForm;
import com.sansan.qiangji.service.impl.device.ScanServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ScanReal {
    private ScanServiceImpl scanService;

    @Resource
    public void setScanService(ScanServiceImpl scanService){
        this.scanService = scanService;
    }

    public List<ScanVO> scanList() {
        List<ScanVO> scanVOS = new ArrayList<>();
        List<Scan> scans = scanService.findAllScan();
        for (Scan scan : scans) {
            ScanVO scanVO = new ScanVO();
            BeanUtils.copyProperties(scan, scanVO);
            scanVOS.add(scanVO);
        }
        return scanVOS;
    }

    @Transactional
    public void scanCreate(ScanAddForm scanAddForm) {
        List<Scan> scans = scanService.findByScanName(scanAddForm.getScanName());
        if (scans.size()!=0){
            log.error("【添加扫码枪】扫码枪已存在");
            throw new ServiceException(ResultEnum.SCAN_IS_EXIST);
        }
        Scan scan = new Scan();
        BeanUtils.copyProperties(scanAddForm, scan);
        scan.setScanOnlineStatus(false);
        scanService.addScan(scan);
    }

    @Transactional
    public void scanEdit(ScanEditForm scanEditForm){
        Scan scan = scanService.findByScanId(scanEditForm.getScanId());
        if (scan == null) {
            log.error("【编辑扫码枪】扫码枪不存在");
            throw new ServiceException(ResultEnum.SCAN_IS_NOT_EXIST);
        }
        BeanUtils.copyProperties(scanEditForm, scan);
        scanService.updateScan(scan);
    }

    @Transactional
    public void deleteScan(Integer scanId) {
        Scan scan = scanService.findByScanId(scanId);
        if (scan == null) {
            log.error("【删除扫码枪】扫码枪不存在");
            throw new ServiceException(ResultEnum.BELT_IS_NOT_EXIST);
        }
        scanService.deleteById(scanId);
    }
}
